<template>
    <a-spin :spinning="loading">
        <div class="container">
            <a-form-model ref="formRef" :model="formData" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                <a-form-model-item label="匹配类别" prop="matchType">
                    <j-dict-select-tag v-model="formData.matchType" placeholder="请选择匹配类别" dictCode="report_tool_match_type" />
                </a-form-model-item>
                <a-form-model-item label="请上传文档" prop="fileList">
                    <a-upload ref="uploadRef" :file-list="fileList" v-model="fileList" name="file" :customRequest="customRequest" :headers="headers" @change="handleUploadChange">
                        <a-button>
                            <!-- <upload-outlined></upload-outlined> -->
                            上传文件
                        </a-button>
                    </a-upload>
                    <a href="/导入模版.xlsx" download>下载模板</a>
                </a-form-model-item>
                <a-form-model-item label="导出模版" prop="expectType">
                    <j-dict-select-tag v-model="formData.expectType" placeholder="请选择导出模版" dictCode="expect_type" />
                </a-form-model-item>
                <div class="form-box">
                    <a-form-model-item style="width:33%" label="地域限制" :label-col="{ span: 9}" :wrapper-col="{ span: 14}">
                        <a-select v-model="formData.provinces" :disabled="provinceDisabled" show-search :filter-option="filterOption" mode="multiple" placeholder="请选择地域限制" @change="provinceChange" :allowClear="true"
                            @search="onProvinceSearch" @popupScroll="onProvinceScroll">
                            <a-select-option :value="item.value" v-for="(item,index) in provinceData" :key="'region'+index">{{item.label}}</a-select-option>
                        </a-select>
                    </a-form-model-item>
                    <a-form-model-item style="width:28%" label="单项匹配数量" prop="matchCount" :label-col="{ span: 8}" :wrapper-col="{ span: 16}">
                        <a-input style="width: 100%" v-model="formData.matchCount" :maxLength="3" placeholder="请选择单项匹配数量"></a-input>
                    </a-form-model-item>
                    <a-form-model-item style="width:35%" label="相似度限制" :label-col="{ span: 8}" :wrapper-col="{ span: 14}">
                        <a-slider style="width: 100%" v-model="formData.similar" :min="0" :max="1" :step="0.1" /><span>{{formData.similar}}</span>
                    </a-form-model-item>
                </div>
                <a-form-model-item label="匹配对象属性" prop="matchCategory ">
                    <j-dict-select-tag v-model="formData.matchCategory " placeholder="请选择匹配对象属性" dictCode="match_category" @change="matchCategoryChange" />
                </a-form-model-item>
                <a-form-model-item label="目标院校名称">
                    <a-select v-model="formData.schoolNames" show-search :filter-option="filterOption" mode="multiple" :disabled="schoolDisabled" placeholder="请选择目标院校名称" @change="schoolChange" :allowClear="true">
                        <a-select-option :value="item.label" v-for="item in schoolData" :key="item.value">{{item.label}}</a-select-option>
                    </a-select>
                </a-form-model-item>
                <div class="btn-box">
                    <a-button type="primary" @click="onSubmit">确认匹配</a-button>
                </div>
            </a-form-model>
        </div>
    </a-spin>
</template>
  <script>
import { getAction, uploadAction } from '@/api/manage'
// import { UploadOutlined } from '@ant-design/icons-vue'
export default {
  name: 'BatchMatching',
  data() {
    return {
      formData: this.$form.createForm(this),
      headers: {
        authorization: 'authorization-text',
      },
      fileList: [],
      rules: {
        matchType: [{ required: true, message: '请选择匹配类别!', trigger: 'change' }],
        expectType: [{ required: true, message: '请选择导出模版!', trigger: 'change' }],
        matchCategory: [{ required: true, message: '请选择匹配对象属性!', trigger: 'change' }],
        fileList: [{ required: true, validator: this.fileRule, trigger: 'change' }],
        matchCount: [{ required: true, validator: this.countRule, trigger: 'blur' }]
      },
      labelCol: { span: 3 },
      wrapperCol: { span: 21 },
      provinceData: [],
      schoolData: [],
      url: {
        province: '/report-tool/region',
        school: '/sys/dict/getDictItems/school_code',
        match: '/report-tool/match',
      },
      loading: false,
      schoolDisabled: true,
      provinceDisabled: false,
      page: {
        pageNo: 1,
        pageSize: 100,
      },
      pageCount: 0,
    }
  },
  watch: {
  },
  mounted() {
    this.loadProvinces()
    this.getSchool()
    this.formData = {
      expectType: null,
      matchType: null,
      schoolNames: [],
      matchCategory: 3,
      provinces: [],
      matchCount: 3,
      similar: 0,
    }
    this.loadAllProvinces();
  },
  created() {

  },
  methods: {
    fileRule(rule, value, callback) {
      if (this.fileList.length === 0) {
        callback(new Error("请上传文件"))
      } else {
        callback()
      }
    },
    countRule(rule, value, callback) {
      if (value > 0 && value <= 200) {
        callback()
      } else if (value > 200) {
        // this.formData.matchCount = 200
        callback(new Error("单项匹配数量不能超过200！"))
      } else {
        callback(new Error("单项匹配数量必须是正整数！"))
      }
    },
    getSchool() {
      getAction(this.url.school).then((res) => {
        if (res.success) {
          this.schoolData = res.result
        }
      })
    },
    onSubmit() {
      this.loading = true
      this.$refs.formRef.validate(valid => {
        if (valid) {
          let provinces = this.formData.provinces ? this.formData.provinces.join(',') : ''
          let schoolNames = this.formData.schoolNames ? this.formData.schoolNames.join(',') : ''
          // 创建 FormData 对象
          let formData = new FormData();
          //   for (let key in this.formData) {
          //     formData.append(key, this.formData[key]);
          //   }
          formData.append('matchType', this.formData.matchType);
          formData.append('expectType', this.formData.expectType);
          formData.append('matchCategory', this.formData.matchCategory);
          formData.append('provinces', provinces);
          formData.append('schoolNames', schoolNames);
          formData.append('matchCount', this.formData.matchCount);
          formData.append('similar', this.formData.similar);
          if (this.fileList.length > 0) {
            formData.append(`file`, this.fileList[0]);
          } else {
            this.$message.error('请选择需要上传的文件');
            return
          }
          uploadAction(this.url.match, formData, { responseType: 'blob' }).then((data) => {
            let fileName = '匹配结果.xlsx';
            if (!data || data.size === 0) {
              this.loading = false
              this.$message.warning('文件下载失败');
              return;
            }
            if (data.success === false) {
              this.$message.error(data.message);
            }
            // 确保 Blob 使用正确的 MIME 类型（可选步骤）
            const blob = data instanceof Blob ? data : new Blob([data], {
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            });
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(blob, fileName);
            } else {
              let url = window.URL.createObjectURL(blob);
              let link = document.createElement('a');
              link.style.display = 'none';
              link.href = url;
              link.setAttribute('download', fileName);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              window.URL.revokeObjectURL(url);
            }
            this.loading = false
            this.fileList = []
            this.formData = {
              expectType: null,
              matchType: null,
              schoolNames: [],
              matchCategory: 3,
              provinces: [],
              matchCount: 3,
              similar: 0,
            }
            this.schoolDisabled = true
            this.provinceDisabled = false
          }).catch(error => {
            console.error('下载失败:', error);
            this.$message.error('下载失败');
            this.loading = false
            this.fileList = []
            this.formData = {
              expectType: null,
              matchType: null,
              schoolNames: [],
              matchCategory: 3,
              provinces: [],
              matchCount: 3,
              similar: 0,
            }
            this.schoolDisabled = true
            this.provinceDisabled = false
          });
        } else {
          this.$message.error('请检查表单填写是否正确');
          this.loading = false
          return false;
        }
      });
    },
    provinceChange(value) {

      if (this.formData.provinces.length > 0 || this.formData.matchCategory != 1) {
        this.formData.schoolNames = [];
        this.schoolDisabled = true
      } else {
        this.schoolDisabled = false
      }
      this.loadProvinces();
    },
    schoolChange(value) {
      if (this.formData.schoolNames.length > 0) {
        this.formData.provinces = []
        this.provinceDisabled = true
      } else {
        this.provinceDisabled = false
      }
    },
    customRequest(e) {
      this.fileList = []
      console.log(e)
      this.fileList[0] = e.file;
    },
    matchCategoryChange(e) {
      console.log(e)
      if (e != 1 || this.formData.provinces.length > 0) {
        this.formData.schoolNames = [];
        this.schoolDisabled = true;
      } else {
        this.schoolDisabled = false;
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
      );
    },
    handleUploadChange(info) {
      if (info.file.status === 'removed') {
        // 处理文件删除逻辑
        this.fileList = info.fileList;
      }
    },
    // 省份加载优化

    loadProvinces() {
      const params = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
      };
      getAction(this.url.province, params).then((res) => {
        if (res.success) {
          this.provinceData = res.result.records.map(item => ({ label: item.name, value: item.name }))
          this.pageCount = res.result.pages
        }
      });
    },
    // 省份滚动加载
    onProvinceScroll(event) {
      if (event.target.scrollTop + event.target.offsetHeight >= event.target.scrollHeight) {
        if (this.page.pageNo < this.pageCount) {
          this.page.pageNo++;
          this.loadProvinces();
        }
      }
    },
    // 获取全部省份
    loadAllProvinces() {
      const params = {
        pageNo: 1,
        pageSize: 4000,
      };
      getAction(this.url.province, params).then((res) => {
        if (res.success) {
          this.allProvinceData = res.result.records.map(item => ({ label: item.name, value: item.name }))
        }
      });
    },
    // 搜索筛选
    onProvinceSearch(searchText) {
      if (searchText) {
        this.provinceData = this.allProvinceData.filter(item => item.label.toUpperCase().indexOf(searchText.toUpperCase()) >= 0)
      } else {
        this.loadProvinces();
      }
    }
  }
}
  </script>
  <style lang="less" scoped>
.container {
  width: 100%;
  height: inherit;
  background: white;
  box-sizing: border-box;
  padding: 30px;
  .btn-box {
    display: flex;
    justify-content: flex-end;
  }
  .form-box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .ant-form-item {
      width: 33%;
    }
  }
  /deep/.ant-form-item-children {
    display: flex;
    .ant-btn {
      margin-right: 10px;
    }
    // .ant-upload-list-item-name {
    //   padding-left: 0;
    // }
    .anticon-loading {
      font-size: 0;
    }
    .ant-progress-outer {
      width: 0;
    }
  }
  /deep/.ant-upload-list-item-card-actions {
    i {
      padding-right: 0;
    }
  }
}
</style>